<template>
    <div class="rights_manage_container">
        <!-- 默认权益 -->
        <div class="title_card">
            <div class="title_card_name">默认权益</div>
        </div>
        <div class="desc">默认权益的服务方式为系统核销，根据在会员权益中的设置规则自动执行。</div>
        <div class="table_card">
            <el-table :data="state.oneList" stripe>
                <el-table-column label="权益名称" prop="priorityInnerName"></el-table-column>
                <el-table-column label="展示名称" prop="priorityOuterName"></el-table-column>
                <el-table-column label="权益图标" prop="remark">
                    <template #default="{ row }">
                        <el-image class="icon_img" :src="row.priorityIcon" fit="cover">
                            <template #error>
                                <div class="icon_error">
                                    <el-icon><icon-picture /></el-icon>
                                </div>
                            </template>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column label="权益简介" :show-overflow-tooltip="true" prop="priorityBrief"> </el-table-column>
                <el-table-column label="权益状态" prop="remark">
                    <template #default="{ row }">
                        <div :class="['status', row.priority?.length > 0 ? 'status_green' : '']">
                            {{ row.priority?.length > 0 ? '已使用' : '未使用' }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" min-width="80">
                    <template #default="{ row }">
                        <el-button class="table-btn" size="small" @click="onEdit(row)" v-auth="'rights:manage:edit'">
                            编辑
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 自定义权益 -->
        <div class="title_card mt_37">
            <div class="title_card_name">自定义权益</div>
        </div>
        <div class="desc">自定义权益的服务方式为线下核销，需商家配合执行。</div>
        <el-button type="primary" @click="onAddRights" v-auth="'rights:manage:add'">添加权益</el-button>
        <div class="table_card">
            <el-table :data="state.twoList" stripe>
                <el-table-column label="权益名称" prop="priorityInnerName"></el-table-column>
                <el-table-column label="展示名称" prop="priorityOuterName"></el-table-column>
                <el-table-column label="权益图标" prop="remark">
                    <template #default="{ row }">
                        <el-image class="icon_img" :src="row.priorityIcon" fit="cover">
                            <template #error>
                                <div class="icon_error">
                                    <el-icon><icon-picture /></el-icon>
                                </div>
                            </template>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column label="权益简介" :show-overflow-tooltip="true" prop="priorityBrief"> </el-table-column>
                <el-table-column label="权益状态" prop="remark">
                    <template #default="{ row }">
                        <div :class="['status', row.priority?.length > 0 ? 'status_green' : '']">
                            {{ row.priority?.length > 0 ? '已使用' : '未使用' }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" class-name="two_btn_tooltip" label="操作" min-width="80">
                    <template #default="{ row }">
                        <el-button class="table-btn" size="small" @click="onEdit(row)" v-auth="'rights:manage:edit'">
                            编辑
                        </el-button>
                        <el-tooltip effect="dark" placement="top" :disabled="!row.priority?.length > 0">
                            <template #content>
                                <div style="max-width: 400px">{{ onTooltip(row) }}</div>
                            </template>
                            <span style="margin-left: 12px">
                                <el-popconfirm
                                    placement="top"
                                    width="200"
                                    cancel-button-type="text"
                                    cancel-button-text="取消"
                                    confirm-button-text="确定"
                                    :icon="WarningFilled"
                                    icon-color="#faad14"
                                    title="确定删除此权益吗?"
                                    @confirm="onDel(row)">
                                    <template #reference>
                                        <el-button
                                            class="table-btn"
                                            size="small"
                                            :disabled="row.priority?.length > 0"
                                            v-auth="'rights:manage:delete'">
                                            删除
                                        </el-button>
                                    </template>
                                </el-popconfirm>
                            </span>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 添加权益 -->
        <div class="dialog_box">
            <el-dialog v-model="state.dialogShow" :title="state.title" width="30%" @closed="onClosed">
                <div class="dialog_content">
                    <div v-if="state.title == '编辑权益'" class="edit_warning">
                        <img
                            class="edit_warning_icon"
                            src="@/assets/imgs/mall/customer/icon-warning-fill@2x.png"
                            alt="" />
                        <div>修改权益后用户端可能会发生变化，请谨慎修改！</div>
                    </div>
                    <el-form ref="formRef" :model="form" :rules="rules">
                        <el-form-item label="权益名称" prop="priorityInnerName">
                            <el-input
                                v-if="state.title == '添加权益'"
                                v-model="form.priorityInnerName"
                                maxlength="10"
                                placeholder="请输入权益名称，不超过10个字，不可修改" />
                            <div v-else>{{ form.priorityInnerName }}</div>
                        </el-form-item>
                        <el-form-item label="展示名称" prop="priorityOuterName">
                            <el-input
                                v-model="form.priorityOuterName"
                                placeholder="请输入展示名称，不超过10个字"
                                maxlength="10"
                                :disabled="state.row.default === 1" />
                            <div class="form_desc">用户端展示的权益名称</div>
                        </el-form-item>
                        <el-form-item label="权益图标" required>
                            <div class="upload_card">
                                <div class="upload_wrap">
                                    <el-upload
                                        action=""
                                        accept=".png"
                                        :show-file-list="false"
                                        :auto-upload="false"
                                        :on-change="onUploadChange">
                                        <div class="upload_btn">
                                            <el-image class="upload_img" :src="form.priorityIcon" fit="cover">
                                                <template #error>
                                                    <div class="upload_img_error">
                                                        <el-icon><icon-picture /></el-icon>
                                                    </div>
                                                </template>
                                            </el-image>
                                        </div>
                                    </el-upload>
                                    <div class="rest_btn" @click="onResetImg">
                                        <el-icon><RefreshRight /></el-icon> 恢复默认
                                    </div>
                                </div>
                                <div class="upload_desc">建议尺寸144*144，限制png格式</div>
                            </div>
                        </el-form-item>
                        <el-form-item label="权益简介" prop="priorityBrief">
                            <el-input
                                v-model="form.priorityBrief"
                                type="textarea"
                                :rows="4"
                                maxlength="100"
                                placeholder="请输入权益简介，不超过100个字" />
                            <div class="form_desc">权益简介将展示在用户端，请认真填写</div>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="state.dialogShow = false">取消</el-button>
                        <el-button type="primary" @click="onCofirm">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import storage from '@/commons/storage';
import { Picture as IconPicture, WarningFilled } from '@element-plus/icons-vue';
import { onMounted, reactive, ref } from 'vue';
import request from '@/request';
import { ElMessage } from 'element-plus';

const formRef = ref(null);
const defaultIconUrl = location.origin + '/imgs/default_rights_icon.png';
const defaultBaoyouUrl = location.origin + '/imgs/baoyou_icon.png';
const defaultJifenUrl = location.origin + '/imgs/jifen_icon.png';
const state = reactive({
    title: '添加权益',
    dialogShow: false,
    corpId: storage.get('ZW-TENANT-ID'),
    tenantId: storage.get('ZW-TENANT-ID'),
    row: {},
    oneList: [],
    twoList: [],
    oneTextTooltips: [],
    twoTextTooltips: [],
    twoBtnTooltips: []
});
const form = reactive({
    corpId: state.corpId,
    // tenantId: state.tenantId,
    priorityInnerName: '',
    priorityOuterName: '',
    priorityIcon: defaultIconUrl,
    priorityBrief: '',
    default: 2,
    appType: 1
});
const rules = reactive({
    priorityInnerName: [{ required: true, message: '该字段必填', trigger: 'blur' }],
    priorityOuterName: [{ required: true, message: '该字段必填', trigger: 'blur' }],
    priorityIcon: [{ required: true, message: '该字段必填', trigger: 'blur' }],
    priorityBrief: [{ required: true, message: '该字段必填', trigger: 'blur' }]
});
const onResetImg = () => {
    let obj = { 包邮: defaultBaoyouUrl, 多倍积分: defaultJifenUrl };
    form.priorityIcon = obj[form.priorityInnerName] || defaultIconUrl;
};

const onTooltip = row => {
    let str = '';
    if (row.priority.length > 0) {
        row.priority.forEach(item => {
            str += `${item?.memberLevelName}、`;
        });
        str = str.substring(0, str.length - 1);
    }
    return `${str}正在使用此权益不可删除`;
};

// 获取列表
const getData = async () => {
    const { data } = await request('getRightsListServ', { corpId: state.corpId, tenantId: state.tenantId });
    let oneList = [];
    let twoList = [];
    data.forEach(item => {
        if (item.default === 1) {
            oneList.push(item);
        } else {
            twoList.push(item);
        }
    });
    state.oneList = oneList;
    state.twoList = twoList;
};
// 添加权益
const onAddRights = () => {
    if (form.id) {
        delete form.id;
    }
    state.title = '添加权益';
    state.dialogShow = true;
};
// 上传图片
const onUploadChange = async file => {
    const suffix = file.raw.name.split('.').pop().toLowerCase();
    if (!['png'].includes(suffix)) {
        ElMessage.error('请上传png格式的图片');
        return;
    }
    const params = new FormData();
    params.append('file', file.raw);
    const { data } = await request('fileUploadServ', params);
    form.priorityIcon = data.url;
};
// 弹框关闭回调
const onClosed = () => {
    state.dialogShow = false;
    formRef.value.resetFields();
    form.corpId = state.corpId;
    form.priorityInnerName = '';
    form.priorityOuterName = '';
    form.priorityIcon = defaultIconUrl;
    form.priorityBrief = '';
    form.default = 2;
    form.appType = 1;
};
// 确定
const onCofirm = async () => {
    if (!formRef.value) return;
    formRef.value.validate(async valid => {
        if (valid) {
            if (state.title == '添加权益') {
                const res = await request('addRightsServ', form);
                state.dialogShow = false;
                getData();
                ElMessage.success('添加成功');
            } else {
                const res = await request('editRightsServ', form);
                state.dialogShow = false;
                getData();
                ElMessage.success('编辑成功');
            }
        }
    });
};

// 编辑
const onEdit = row => {
    state.title = '编辑权益';
    state.row = row;
    state.dialogShow = true;
    form.id = row.id;
    form.priorityInnerName = row.priorityInnerName;
    form.priorityOuterName = row.priorityOuterName;
    form.priorityIcon = row.priorityIcon;
    form.priorityBrief = row.priorityBrief;
    form.default = row.default;
    form.appType = row.appType;
};
// 删除
const onDel = async row => {
    const res = await request('delRightsServ', { id: row.id });
    getData();
    ElMessage.success('删除成功');
};

onMounted(() => {
    getData();
});
</script>

<style lang="scss" src="./index.scss" scoped></style>
